package com.agp.controller.user;

import com.agp.constant.JwtClaimsConstant;
import com.agp.constant.MessageConstant;
import com.agp.context.BaseContext;
import com.agp.dto.PasswordDTO;
import com.agp.dto.UserDTO;
import com.agp.dto.UserLoginDTO;
import com.agp.dto.UserRegisterDTO;
import com.agp.entity.User;
import com.agp.exception.AccountNotFoundException;
import com.agp.properties.JwtProperties;
import com.agp.result.Result;
import com.agp.service.UserService;
import com.agp.utils.JwtUtil;
import com.agp.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;



@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户相关接口")
@Validated
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户注册
     *
     * @param userRegisterDTO
     */
    @PostMapping("/register")
    @ApiOperation("用户注册接口")
    public Result register(@RequestBody @Validated UserRegisterDTO userRegisterDTO) {
        log.info("用户注册，用户信息为：{}", userRegisterDTO);
        Boolean checkPhone = userService.checkPhone(userRegisterDTO.getPhone());
        if (checkPhone) {
            throw new AccountNotFoundException(MessageConstant.PHONE_HAS_BEEN_REGISTERED);
        }
        userService.register(userRegisterDTO);
        return Result.success();
    }

    /**
     * 用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody @Validated UserLoginDTO userLoginDTO,
                                     @RequestParam(required = true) boolean isPasswordLogin) {
        log.info(" 用户登录，登录信息为：{}--{}", userLoginDTO, isPasswordLogin);

        User user = userService.login(userLoginDTO,isPasswordLogin);
        // 登录成功后，生成jwt令牌返回给用户
        // jwt 数据部分
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getSecretKey(),// 密钥
                jwtProperties.getTtlMillis(), // 过期时间
                claims);// 数据
        log.info("用户登录成功，生成jwt令牌：{}", token);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .username(user.getNickname())
                .avatar(user.getAvatar())
                .token(token)
                .role(user.getRole())
                .build();
        return Result.success(userLoginVO);
    }


    /*
   请求方式：get
    路径：/user/
    */
    @GetMapping
    public Result<User> getUserInfo(){
        //要查询的字段，除了密码全都要查询出来
        Long userId = BaseContext.getCurrentId();
        User user = userService.findById(userId);

        return Result.success(user);

    }

   @PutMapping("update")
   @ApiOperation("修改用户信息")

    public Result<String> updateUserInfo(@RequestBody UserDTO userDTO){
        log.info("修改用户信息，用户信息为：{}", userDTO);
       userService.updateUserInfo(userDTO);
       return Result.success("用户信息更新成功");

    }

    //修改密码
    @PutMapping("updatePassword")
    @ApiOperation("修改密码")
    public Result<String> updatePassword(@RequestBody @Validated PasswordDTO passwordDTO){
        log.info("修改密码，用户信息为：{}", passwordDTO);
        userService.updatePassword(passwordDTO);
        return Result.success("密码修改成功");
    }

}
